package com.liu.stockmarket.ui.setting

import androidx.lifecycle.*
import com.liu.stockmarket.VO.Backup
import com.liu.stockmarket.repository.database.ProfitRepository
import com.liu.stockmarket.repository.database.StockRepository
import com.liu.stockmarket.repository.database.TransactionRecordRepository
import com.liu.stockmarket.utils.YMDParse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class SettingsViewModel(
    private val transactionRecordRepository: TransactionRecordRepository,
    private val stockRepository: StockRepository,
    private val profitRepository: ProfitRepository
) : ViewModel() {

    private val _data = MutableLiveData<Backup>()
    val data: LiveData<Backup> = _data

    fun getData(playDate: String?) {
        viewModelScope.launch(Dispatchers.IO) {
            val transactionRecords = transactionRecordRepository.queryAll()
            val stocks = stockRepository.queryAll()
            val profits = profitRepository.queryAll()
            _data.postValue(Backup(transactionRecords, stocks,profits,playDate?.YMDParse()))
        }

    }

    fun saveData(backup: Backup) {
        viewModelScope.launch(Dispatchers.IO){
            if(!backup.transactionRecords.isNullOrEmpty()){
                transactionRecordRepository.deleteAllForSaveAll(backup.transactionRecords)
            }
            if (!backup.stocks.isNullOrEmpty()) {
                stockRepository.deleteAllForSaveAll(backup.stocks)
            }
            if (!backup.profits.isNullOrEmpty()) {
                profitRepository.deleteAllForSaveAll(backup.profits)
            }
        }
    }

    /**
     * 清空所有数据
     */
    fun clearData() {
        viewModelScope.launch(Dispatchers.IO) {
            transactionRecordRepository.deleteAll()
            stockRepository.deleteAll()
            profitRepository.deleteAll()
        }
    }

    class SettingsViewModelFactory(
        private val transactionRecordRepository: TransactionRecordRepository,
        private val stockRepository: StockRepository,
        private val profitRepository: ProfitRepository
    ) :
        ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            @Suppress("UNCHECKED_CAST")
            return SettingsViewModel(
                transactionRecordRepository,
                stockRepository,
                profitRepository
            ) as T
        }

    }
}